"""
Used to manage language strings:
 - Normal strings use PO/MO
 - User customized strings saved in user.lang file
 - changing languages on-the-fly is handled by the update function
"""

import wx
import os
import gettext
from configreader import ConfigReader

class Lang(object):
    """
    Used for costumizable lables (lists, statusbar etc..)
    """
    def __init__(self, utility):
        
        # Set up user language file (stored in user's config directory)
        self.user_lang = None
        user_filepath = os.path.join(utility.getConfigPath(), 'user.lang')
        self.user_lang = ConfigReader(user_filepath, "BitTornado/language")

        # User translation, cache for optimization
        self.cache =  {}

        # Default translation
        self.base = {}
        
    def get(self, label):
        """
        Returns a label from the user.lang
        Falls back to normal translation if not exists
        """
        # if in cache...
        if label in self.cache:
            return self.cache[label]

        # read from user.lang
        if self.user_lang is not None and self.user_lang.Exists(label):
            text = self.user_lang.Read(label)
            self.cache[label] = text
            return text
        
        # fall back
        return self.getDefault(label)

    def getDefault(self, label):
        """
        Returns a label from the normal translation file
        """
        if label in self.base:
            return self.base[label]
        return _(label)
    
    def flush(self):
        """
        Saves changes in disk
        """
        if self.user_lang is not None:
            self.user_lang.DeleteEntry("dummyparam", False)
            self.user_lang.Flush()
        self.cache = {}
    
    def writeUser(self, label, text):
        """
        writes a new string to user.lang
        """
        change = False
        
        text_user = self.get(label)
        text_nonuser = self.getDefault(label)
               
        user_lang = self.user_lang
        
        # The text string is the default string
        if text == text_nonuser:
            # If there was already a user string, delete it
            # (otherwise, do nothing)
            if text_user != "":
                user_lang.Write("exampleparam", "example value")
                user_lang.DeleteEntry(label)
                change = True
        elif text != text_user:
            # Only need to update if the text string differs
            # from what was already stored
            user_lang.Write(label, text)
            change = True
        
        return change

    def loadLanguages(self):
        """
        Load languages
        """
        self.language_options = {_("Default"): wx.LANGUAGE_DEFAULT}
        
        try:
            file = open(os.path.join(utility.getSharePath(), 'locale', 'languages.list'), "r")
            lines = file.readlines()
            file.close()
        except:
            lines = []
        
        for line in lines:
            line = line.strip()
            if not line or line[0] in ('#', ';'):
                continue
            try:
                self.language_options[wx.Locale.GetLanguageName(getattr(wx, line))] = getattr(wx, line)
            except:
                print "unable to load language:", line
        
    def update(self, langid):
        """
        Changes the language of the GUI
        """
        
        # Currently disabled
        return False

        # No change...
        if wx.GetApp().langid == langid:
            return False
        
        wx.GetApp().langid = langid
        # change language: this will take care of any new window
        localedir = os.path.join(utility.getSharePath(), "locale")
        domain = "messages"
        locale = wx.Locale(langid)
        wx.GetApp().translation = gettext.translation(domain, localedir,
                [locale.GetCanonicalName()], fallback = True)
        wx.GetApp().translation.install(unicode=True)

        # update all actions
        utility.makeactionlist()
        for action in utility.actions.values():
            if hasattr(action, "loadTranslation"):
                action.loadTranslation()
        
        # update all lists
        for list in utility.lists:
            list.loadTranslation(True)

        # update Statusbar
        utility.frame.GetStatusBar().loadTranslation()
        
        # update menubar
        utility.frame.GetMenuBar().updateMenu()

        # update toolbar
        utility.frame.tb.updateItems()

        # update menu check
        utility.frame.updateMenuChecks()
        
        return True
